<%@ WebHandler Language="C#" Class="ViewContent" %>
using System;
using System.Web;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using Memories;
using Memories.Entities;

public class ViewContent : IHttpHandler
{
    string path = "";
	string type = "full";
	int imagewidth = 0;
	int border = 4;
        
	public void ProcessRequest (HttpContext context){

        Memories.Entities.File file = null;
        Settings setting = (Settings)context.Items["Settings"];
        path = (string)context.Items["Path"];
        file = MemoriesDB.GetFile(setting, path);
		
       

        if (context.Request.Params["ImageWidth"] != null && context.Request.Params["ImageWidth"] != "")
        {
			imagewidth = Int32.Parse(context.Request.Params["ImageWidth"]);
		}

		

        if (file != null)
        {

            context.Response.ContentType = "image/pjpeg";

            if (imagewidth < 1)
            {
                context.Response.WriteFile(file.FullName);
            }
            else
            {
                string filepath = getSavePath(setting, path,imagewidth);

                if (!System.IO.File.Exists(filepath) || System.IO.File.GetLastWriteTime(filepath) < file.LastWriteTime)
                {
                    if (imagewidth <= 100)
                    {
                        saveResizedImageSquare(file.FullName, filepath, imagewidth, border);
                    }
                    else
                    {
                        saveResizedImage(file.FullName, filepath, imagewidth, border);
                    }
                }

                context.Response.WriteFile(filepath);
            }
            

        }

    }

	public bool IsReusable{
		get { return true; }
	}

    string  getSavePath(Settings settings,string path,int size)
    {
        return settings.TempPath.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar +  settings.HostHeader + "_" + path.Replace('/', '_') + size.ToString();
    }


	void saveResizedImage(string imgPath,string savePath,int maxWidth,int border){

        using (System.Drawing.Bitmap imgIn = new System.Drawing.Bitmap(imgPath))
        {
            float y = imgIn.Height;
            float x = imgIn.Width;
            float factor;
            if (x > maxWidth || y > maxWidth)
            {
                if (x >= y)
                {
                    factor = maxWidth / x;
                }
                else
                {
                    factor = maxWidth / y;
                }

                using (System.Drawing.Bitmap imgOut = new Bitmap((int)(x * factor) + border * 2, (int)(y * factor) + border * 2, PixelFormat.Format24bppRgb))
                {
                    imgOut.SetResolution(imgIn.HorizontalResolution, imgIn.VerticalResolution);
                    using (Graphics g = Graphics.FromImage(imgOut))
                    {
                        g.Clear(Color.White);
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(imgIn, new RectangleF(border, border, (factor * x), (factor * y)), new RectangleF(0, 0, x, y), GraphicsUnit.Pixel);
                        g.DrawRectangle(new System.Drawing.Pen(Color.White, 1), border, border, (int)(x * factor), (int)(y * factor));
                        g.Dispose();
                    }
                    
                    imgOut.Save(savePath, imgIn.RawFormat);

                }
              
            }
            else
            {
                System.IO.File.Copy(imgPath, savePath, true);
            }

        }
	}

    void saveResizedImageSquare(string imgPath, string savePath, int maxWidth, int border)
    {

        using (System.Drawing.Bitmap imgIn = new System.Drawing.Bitmap(imgPath))
        {
            float y = 0;
            float x = 0;
            float minside = 0;
            float factor;
            if (imgIn.Height >= imgIn.Width)
            {
                minside = imgIn.Width;
                y = (imgIn.Height - imgIn.Width) / 2;
            }
            else
            {
                minside = imgIn.Height;
                x = (imgIn.Width - imgIn.Height) / 2;
            }

            using (System.Drawing.Bitmap imgOut = new Bitmap(maxWidth, maxWidth, PixelFormat.Format24bppRgb))
            {
                imgOut.SetResolution(imgIn.HorizontalResolution, imgIn.VerticalResolution);
                using (Graphics g = Graphics.FromImage(imgOut))
                {
                    g.Clear(Color.White);
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(imgIn, new RectangleF(0, 0, imagewidth, imagewidth), new RectangleF(x, y, minside, minside), GraphicsUnit.Pixel);
                    g.DrawRectangle(new System.Drawing.Pen(Color.White, border), border / 2, border / 2, maxWidth - border, maxWidth - border);
                    g.Dispose();
                }

                imgOut.Save(savePath, imgIn.RawFormat);

            }
        }
    }
}
